package com.csi.dao.impl;

import com.csi.dao.RoomDao;
import com.csi.domain.Room;
import com.csi.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoomDaoImpl extends JDBCUtils implements RoomDao {
    @Override
    public List<Room> findAll(int typeId) throws SQLException {
//        查询同一类型中的所以有房间
        final String sql="select*from hotel_room where typeId=?";

        //调用jdbc
        Connection connection = this.getConnection();
//调用sql语句
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setInt(1,typeId);

        ResultSet rs = ps.executeQuery();


        List<Room> rooms=new ArrayList();

        while (rs.next()){
            Room room=new Room();
            room.setRoomState(rs.getInt("roomState"));
            room.setRoomId(rs.getInt("roomId"));
            room.setRoomNO(rs.getString("roomNo"));
            room.setTypeId(typeId);
            rooms.add(room);
        }
        this.release(rs,ps,connection);


        return rooms;
    }

    @Override
    public int add(Room room) throws SQLException {
        final  String sql="insert into hotel_room(roomNO,typeId,roomState) value(?,?,?)";
        Connection connection = this.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setString(1, room.getRoomNO());
        ps.setInt(2,room.getTypeId());
        ps.setInt(3,room.getRoomState());

        int i = ps.executeUpdate();

        this.release(ps,connection);
        return i;
    }

    @Override
    public int delete(int RoomId) throws SQLException {
        final String sql ="delete from hotel_room where RoomId=?";

        Connection connection = this.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setInt(1,RoomId);
        int i = ps.executeUpdate();

        this.release(ps,connection);

        return i;
    }

    @Override
    public int update(Room room) throws SQLException {
        final  String sql="update hotel_room set  roomNo=?,typeId=?,roomState=? where roomId=?";

        Connection connection = this.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,room.getRoomNO());
        ps.setInt(2,room.getTypeId());
        ps.setInt(3,room.getRoomState());
        ps.setInt(4,room.getRoomId());


        int i = ps.executeUpdate();
        this.release(ps,connection);


        return i;
    }
}
